local skynet = require "skynet"
local gateserver = require "handle_websocket_gateserver"
local log = require "sky_log"

local CMD = {}
local watchdog
local connection = {}	-- [fd] -> connection : { fd , client, agent , ip, mode }
local forwarding = {}	-- [agent] -> connection

skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
}

local function unforward(c)
	if c.agent then
		forwarding[c.agent] = nil
		c.agent = nil
		c.client = nil
	end
end

local function close_fd(fd)
	local c = connection[fd]
	if c then
		unforward(c)
		connection[fd] = nil
	end
end

local handler = {}
function handler.open(source, conf)
	watchdog = conf.watchdog or source
end

function handler.connect(fd, addr)
	local c = {
		fd = fd,
		ip = addr,
	}
	connection[fd] = c
	skynet.send(watchdog, "lua", "socket", "open", fd, addr)
end

function handler.query_tables()
	log.info("gate query_tables connection= ", connection)
	log.info("gate query_tables forwarding= ", forwarding)
	skynet.send(watchdog, "lua", "query_tables")
end

--============================= CMD =============================--
function CMD.forward(source, fd, client, address)
	local c = assert(connection[fd])
	unforward(c)
	c.client = client or 0
	c.agent = address or source
	forwarding[c.agent] = c
	--log.info("forwarding=", forwarding)

	--gateserver.openclient(fd, c.ip)
	skynet.send(c.agent, "lua", "openclient", fd, c.ip)
end

function CMD.disconnect(agent, fd)
	close_fd(fd)
	skynet.send(watchdog, "lua", "socket", "close", fd)
end

function CMD.error(agent, fd, msg)
	close_fd(fd)
	skynet.send(watchdog, "lua", "socket", "error", fd, msg)
end

function handler.command(cmd, source, ...)
	local f = assert(CMD[cmd])
	return f(source, ...)
end

gateserver.start(handler)
